package com.bby.user.manager;

import com.bby.common.exception.BBYException;
import com.bby.common.model.UserBusinessInfo;
import com.bby.common.model.UserCustomInfo;
import com.bby.common.model.UserPublicInfo;
import com.bby.common.utils.BBYUtils;
import com.bby.common.utils.StatusCode;
import com.bby.user.bean.UserInfo;
import com.mongodb.client.result.UpdateResult;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
import static org.springframework.data.mongodb.core.query.Update.update;

@Component
public class UserinfoManager {
    private MongoTemplate mongoTemplate;
    public static String BUSINESS_COLLECTION = "userBusinessInfo";
    public static String CUSTOM_COLLECTION = "userCustomInfo";
    public UserinfoManager(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }
    
    // 添加
    public UserCustomInfo saveCustomInfo(UserCustomInfo userInfo){
        return mongoTemplate.save(userInfo);
    }
    public UserBusinessInfo saveBusinessInfo(UserBusinessInfo userInfo){
        return mongoTemplate.save(userInfo);
    }

    // 删除
    public void deleteCustomInfo(String userId) throws BBYException {
        checkId(userId);
        mongoTemplate.remove(
        query(where("_id").is(new ObjectId(userId))), CUSTOM_COLLECTION).getDeletedCount();
    }
    public void deleteBusinessInfo(String userId) throws BBYException {
        checkId(userId);
        mongoTemplate.remove(
                query(where("_id").is(new ObjectId(userId))),
                BUSINESS_COLLECTION).getDeletedCount();
    }

    private void checkId(String userId) throws BBYException {
        if (!isExists(userId)){
            throw new BBYException(StatusCode.USER_NOT_FOUND,"用户不存在！");
        }
    }
    // 找查
    public boolean isExists(String userId){
        return mongoTemplate.exists(query(where("_id").is(new ObjectId(userId))),CUSTOM_COLLECTION);
    }
    public boolean isNameExists(String username){
        return mongoTemplate.exists(query(where("username").is(username)),CUSTOM_COLLECTION);
    }
    public boolean isEmailExists(String email){
        return mongoTemplate.exists(query(where("email").is(email)),CUSTOM_COLLECTION);
    }
    public UserCustomInfo findUserCustomInfoById(String userId) throws BBYException {
        checkId(userId);
        return mongoTemplate.findById(userId,UserCustomInfo.class);
    }

    public UserBusinessInfo findUserBusinessInfoById(String userId) throws BBYException {
        checkId(userId);
        return mongoTemplate.findById(userId,UserBusinessInfo.class);
    }
    public UserCustomInfo findUserCustomInfoByName(String username) throws BBYException {
        if (!isNameExists(username)){
            throw new BBYException(StatusCode.USER_NOT_FOUND,"用户不存在！");
        }
        return mongoTemplate.findOne(query(where("username").is(username)),UserCustomInfo.class);
    }
    public UserCustomInfo findUserCustomInfoByEmail(String email) throws BBYException {
        if (!isNameExists(email)){
            throw new BBYException(StatusCode.USER_NOT_FOUND,"用户不存在！");
        }
        return mongoTemplate.findOne(query(where("email").is(email)),UserCustomInfo.class);
    }
    public UserInfo findUserInfoById(String userId) throws BBYException {
        return new UserInfo(findUserBusinessInfoById(userId),findUserCustomInfoById(userId));
    }
    
    // 修改
    public void updateBirthday(String userId, Date birthday) throws BBYException {
        checkId(userId);
        mongoTemplate.updateFirst(
                query(where("_id").is(new ObjectId(userId))),
                update("birthday",birthday),
                CUSTOM_COLLECTION).getModifiedCount();
    }
    public void updateCustomInfoById(String userId, String key, Object value) throws BBYException {
        checkId(userId);
        if (!key.matches("username|email|signature|birthday|sex")) {
            throw new BBYException(StatusCode.INPUT_ERROR, "参数错误");
        }
        UpdateResult result = mongoTemplate.updateFirst(
                query(where("_id").is(userId)),
                update(key, value), CUSTOM_COLLECTION);
        if (result.getModifiedCount()==0){
            throw new BBYException("修改失败！");
        }
    }
    public void updateCustomInfoById(UserCustomInfo customInfo) throws BBYException {
        checkId(customInfo.getUserId());
        mongoTemplate.save(customInfo);
    }


    public List<UserCustomInfo> findCustomInfos(Set<String> ids) {
        Query query = new Query(Criteria.where("_id").in(ids));
        return mongoTemplate.find(query,UserCustomInfo.class);
    }

    public void updatePassword(String userId, String newPw) throws BBYException {
        Query query = new Query(Criteria.where("_id").in(userId));
        Update update = new Update().set("password",newPw);
        UpdateResult result = mongoTemplate.updateFirst(query,update,UserBusinessInfo.class);
        if (result.getModifiedCount()==0){
            System.out.println(result);
            throw new BBYException("修改失败！");
        }
    }

    /**
     * 不存在的将被忽略
     * @param ids
     */
    public List<UserPublicInfo> findUserPublicInfoByIds(List<String> ids) {
        List<UserPublicInfo> list = new ArrayList<>();
        for (String id : ids) {
            UserCustomInfo info = mongoTemplate.findById(id,UserCustomInfo.class);
            if (info!=null) {
                list.add(new UserPublicInfo(info));
            }
        }
        return list;
    }

    public void updateCustom(String userId, String key, String value) throws BBYException {
        Query query = new Query(Criteria.where("_id").in(userId));
        Object v = value;
        if (key.equals("birthday")){
            v = BBYUtils.toBirthdayDate(value);
        }
        Update update = new Update().set(key,v);
        UpdateResult result = mongoTemplate.updateFirst(query,update,UserCustomInfo.class);
        if (result.getModifiedCount()==0){
            System.out.println(result);
            throw new BBYException("修改失败！");
        }
    }
}
